package com.dream.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Component;

import com.dream.common.Common;
import com.dream.common.DateTools;
import com.dream.common.SuperDao;
import com.dream.model.SysUser;
import com.dream.model.Sys_Class;
import com.dream.model.Sys_Dict;
import com.dream.model.Sys_Room;
import com.dream.model.Sys_Room_Position;
import com.dream.model.Sys_Room_Position_User;
import com.dream.model.Sys_User_Class;
import com.dream.system.service.ISysClass;

@Component("sysClassServiceImpl")
public class SysClassServiceImpl extends SuperDao<Object> implements ISysClass {

	@SuppressWarnings("unchecked")
	@Override
	public int addSysClass(Sys_Class model) {
		// TODO Auto-generated method stub
		// 他是一个集团
		if (null == model.getType() || "".equals(model.getType()) || "1".equals(model.getType())) {
			String hql = "select count(*) from Sys_Class t where t.name = ? and t.type = 1 ";
			Object[] obj = new Object[] { model.getName() };
			int count = this.getListCount(hql, obj, "");
			if (count > 0) {
				return 2;
			}
			model.setCid(UUID.randomUUID().toString());
			model.setCreateTime(Common.getTime1());
			model.setShowTime(Common.getTime());
			model.setLv(0);
			model.setOpen(1);
			model.setCpassword("");
			model.setpName(model.getName());
			this.addT(model);
			return 1;
		}
		// 增加一个学校
		if ("2".equals(model.getType())) {
			String hql = "select count(*) from Sys_Class t where t.name = ? and t.type = 2 and t.cpid =? ";
			Object[] obj = new Object[] { model.getName(), model.getCpid() };
			int count = this.getListCount(hql, obj, "");
			if (count > 0) {
				return 2;
			}
			model.setCid(UUID.randomUUID().toString());
			model.setCreateTime(Common.getTime1());
			model.setShowTime(Common.getTime());
			model.setCpassword("");
			model.setLv(0);
			model.setOpen(1);
			model.setpName(model.getpName() + "-" + model.getName());
			this.addT(model);
			return 1;
		}
		// 增加一个年级
		if ("3".equals(model.getType())) {

			String sql = " from Sys_Dict t where t.dictSign ='allLv' and t.value1 = ? ";
			Object[] object = new Object[] { model.getLv() + "" };
			List<Sys_Dict> list = this.getList(sql, object, 0, 0, "");
			String pName = "";
			if (null != list && list.size() > 0) {
				Sys_Dict sd = list.get(0);
				pName = sd.getDictName();

			} else {
				return 0;
			}

			// 如果是一个年级，则需要先增加一个年级，在增加一个班
			String hql = "from Sys_Class t where t.name = ?  and t.cpid =? ";
			Object[] obj = new Object[] { pName, model.getCpid() };
			List<Sys_Class> listsc = this.getList(hql, obj, 0, 0, "");
			if (null != listsc && listsc.size() > 0) {
				Sys_Class sc = listsc.get(0);
				Object[] obj1 = new Object[] { model.getName(), sc.getCpid() };
				List<Sys_Class> cs1 = this.getList(hql, obj1, 0, 0, "");
				if (null != cs1 && cs1.size() > 0) {
					return 2;
				} else {

					model.setCid(UUID.randomUUID().toString());
					model.setCreateTime(Common.getTime1());
					model.setShowTime(Common.getTime());
					model.setpName(sc.getpName() + "-" + model.getName());
					model.setType("4");
					model.setCpid(sc.getCid());
					boolean b = this.Validate(model);
					if (b == true) {
						this.addT(model);
					} else {
						return 2;
					}

				}
			} else {
				Sys_Class sc = new Sys_Class();

				sc.setName(model.getName());
				sc.setCpassword(model.getCpassword());
				String sqlg = "from Sys_Class t where t.cid = ? ";
				Object[] objcet1 = new Object[] { model.getCpid() };
				List<Sys_Class> listc = this.getList(sqlg, objcet1, 0, 0, "");
				if (listc == null || listc.size() <= 0) {
					return 0;
				}

				model.setCid(UUID.randomUUID().toString());
				model.setCreateTime(Common.getTime1());
				model.setShowTime(Common.getTime());
				model.setName(pName);
				model.setpName(listc.get(0).getpName() + "-" + model.getName());
				model.setType("3");
				model.setCpassword("");
				this.addT(model);

				sc.setCid(UUID.randomUUID().toString());
				sc.setCreateTime(Common.getTime1());
				sc.setShowTime(Common.getTime());
				sc.setCpid(model.getCid());
				sc.setLv(model.getLv());
				sc.setpName(model.getpName() + "-" + sc.getName());
				sc.setType("4");

				this.addT(sc);

			}

			return 1;
		}
		return 0;
	}

	// 验证这个班在系统中存在不
	public boolean Validate(Sys_Class sc) {
		String hql = "select count(*) from Sys_Class t where t.cpid = ? and t.name = ?";
		Object[] objcet = new Object[] { sc.getCpid(), sc.getName() };
		int count = this.getListCount(hql, objcet, "");
		if (count > 0) {
			return false;
		}
		return true;
	}

	@SuppressWarnings("all")
	@Override
	public Map getAllClass() {
		// TODO Auto-generated method stub
		String hsql = " from  Sys_Class t";
		@SuppressWarnings("unchecked")
		List<SysUser> list1 = (List<SysUser>) this.getList(hsql, 0, 0, "");
		int count = this.getListCount("select count(*) " + hsql, "");
		Map map = new HashMap();
		map.put("count", count);
		map.put("list", list1);
		map.put("sum", count);
		return map;
	}

	@SuppressWarnings("all")
	@Override
	public int deleteClass(Sys_Class model) {
		if (model.getpName() == null || "".equals(model.getpName())) {
			return 0;
		}
		String hql = "from Sys_Class t where t.pName like '%" + model.getpName() + "%'";
		List<Sys_Class> list = this.getList(hql, 0, 0, "");
		for (int i = 0; i < list.size(); i++) {
			Sys_Class su = (Sys_Class) this.getT(new Sys_Class(), list.get(i).getTable_id());
			this.delete(su);
		}
		return 1;
	}

	@Override
	public int updateClass(Sys_Class model) {
		// TODO Auto-generated method stub
		Sys_Class sc = (Sys_Class) this.getT(new Sys_Class(), model.getTable_id());
		if (sc == null) {
			return 0;
		} else {
			if (null != model.getCpassword() && !"".equals(model.getCpassword())) {
				sc.setCpassword(model.getCpassword());
			}
			if (null != model.getAddresss() && !"".equals(model.getAddresss())) {
				sc.setAddresss(model.getAddresss());
			}
			if (null != model.getName() && !"".equals(model.getName())) {

				String name = this.getParentName(sc.getCpid());
				if (null == name || "0".equals(sc.getCpid())) {
					sc.setpName(model.getName());
					sc.setName(model.getName());
				} else {
					sc.setpName(name + "-" + model.getName());
					sc.setName(model.getName());
				}
				// 上面是先将自己这条数据的问题解决好，在解决自己所有的下级
				this.updateT(sc);
				forclass(sc);

				return 1;
			}

			this.updateT(sc);

		}

		return 1;
	}

	/**
	 * 递归更新
	 * 
	 * @param listc
	 * @param sc
	 */
	@SuppressWarnings("all")
	public void forclass(Sys_Class sc) {

		List<Sys_Class> listc1 = this.getChilde(sc.getCid());
		// 如果有下级
		if (null != listc1 && listc1.size() > 0) {
			for (int i = 0; i < listc1.size(); i++) {
				Sys_Class sct = listc1.get(i);
				sct.setpName(sc.getpName() + "-" + sct.getName());
				this.updateT(sct);
				forclass(sct);
			}

		}
	}

	/**
	 * 得到自己的上级名称
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getParentName(String cpid) {
		// 找到自己的上级
		Object[] objcet2 = new Object[] { cpid };
		String sqlg1 = "from Sys_Class t where t.cid = ? ";
		List<Sys_Class> listc2 = this.getList(sqlg1, objcet2, 0, 0, "");
		if (null == listc2 || listc2.size() <= 0) {
			return null;
		}
		return listc2.get(0).getpName();
	}

	/**
	 * 得到自己的所有下级
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Sys_Class> getChilde(String cid) {
		// 找到自己的上级
		Object[] objcet2 = new Object[] { cid };
		String sqlg1 = "from Sys_Class t where t.cpid = ? ";
		List<Sys_Class> listc2 = this.getList(sqlg1, objcet2, 0, 0, "");
		if (null == listc2 || listc2.size() <= 0) {
			return null;
		}
		return listc2;
	}

	/**
	 * 设置学生和老师的所在学校和班级的问题
	 */
	@SuppressWarnings("all")
	@Override
	public int addTeacherAddClass(List<Sys_Class> list, String teacherId) {
		// TODO Auto-generated method stub
		if (null == list || list.size() <= 0) {
			return 0;
		}
		SysUser su = new SysUser();
		su.setTable_id(teacherId);
		SysUser su1 = (SysUser) this.getT(new SysUser(), su.getTable_id());
		// 如果他是一个学生,就要把他原来读的哪个班的在读，清为过往读
		if (su1 != null && "1".equals(su1.getUserType())) {
			String hql2 = "from Sys_User_Class t where t.sysUser.table_id = ? and t.state ='1' ";
			Object[] obj = new Object[] { teacherId };
			List<Sys_User_Class> sulist = this.getList(hql2, obj, 0, 0, "");
			if (null != sulist && sulist.size() > 0) {
				for (int i = 0; i < sulist.size(); i++) {
					Sys_User_Class suc = sulist.get(i);
					suc.setState("0");
					this.updateT(suc);
				}
			}
		}
		// 老师的逻辑
		String year = DateTools.getCurrentYear();
		String hql = " select count(*) from Sys_User_Class t where t.sysUser.table_id = ? and t.sys_Class.table_id = ? and t.year = ? ";
		Object[] obj = null;

		String sql = "from Sys_User_Class t where t.sysUser.table_id = ?   and t.year <> ?";
		obj = new Object[] { teacherId, year };
		// 先将以前的数据置为-1，表示离去
		List<Sys_User_Class> suclist = this.getList(sql, obj, 0, 0, "");
		if (null != suclist) {
			for (int i = 0; i < suclist.size(); i++) {
				Sys_User_Class s1 = suclist.get(i);
				s1.setState("-1");
				this.updateT(s1);
			}
		}
		// 在将现这一年的数据删除掉,如果在这一个班数据 删除掉
		String sql1 = "delete from Sys_User_Class t where t.sysUser.table_id = ? and t.sys_Class.table_id = ?   and t.year = ? ";
		for (int i = 0; i < list.size(); i++) {
			obj = new Object[] { teacherId, list.get(i).getTable_id(), year };
			this.deleteT(sql1, obj);
		}
		String sqlyear = "select max(year) from Sys_User_Class t";
		String cyear = DateTools.getCurrentYear();
		List listyare = this.getList(sqlyear, 0, 11, "");
		if (listyare != null) {
			cyear = listyare.get(0).toString();
		}
		for (int i = 0; i < list.size(); i++) {
			Sys_Class sc = list.get(i);
			Sys_User_Class suc = new Sys_User_Class();
			suc.setSys_Class(sc);
			suc.setSysUser(su);
			suc.setYear(cyear);
			obj = new Object[] { teacherId, sc.getTable_id(), year };
			if ("4".equals(sc.getType())) {
				suc.setState("1");
			} else {
				suc.setState("0");
			}
			this.addT(suc);
		}

		return 1;
	}

	/**
	 * 更新学校的作业习时间表
	 */
	@Override
	public int updateClassLreanTime(Sys_Class model) {
		// TODO Auto-generated method stub
		if (null == model || model.getTable_id() == null || "".equals(model.getTable_id())) {
			return 0;
		}
		Sys_Class sc = (Sys_Class) this.getT(new Sys_Class(), model.getTable_id());
		sc.setTimeLearn(model.getTimeLearn());
		this.updateT(sc);
		return 1;
	}

	@Override
	public Sys_Class getClassLreanTime(Sys_Class model) {
		// TODO Auto-generated method stub
		if (null == model || model.getTable_id() == null || "".equals(model.getTable_id())) {
			return null;
		}
		Sys_Class sc = (Sys_Class) this.getT(new Sys_Class(), model.getTable_id());
		return sc;
	}

	/**
	 * 增加一个班级的教室
	 */
	@Override
	@SuppressWarnings("all")
	public int addClass_Room(Sys_Room model, String arr) {
		// TODO Auto-generated method stub
		if (arr.length() <= 0) {
			return 0;
		}
		if (null == model) {
			return 0;
		}
		if (null == model.getX1() || 0 == model.getX1()) {
			return 0;
		}
		if (null == model.getY1() || 0 == model.getY1()) {
			return 0;
		}
		List<Sys_Room_Position> srlist = (List<Sys_Room_Position>) JSONArray.toCollection(JSONArray.fromObject(arr), Sys_Room_Position.class);

		// 增加教室之前要先将之前这个班的教室禁用掉，只让当前的教室启用
		String hql = "from Sys_Room t where t.sysUser.table_id = ? and state='1' and t.sys_Class.table_id = ? ";
		Object[] object = new Object[] { model.getSysUser().getTable_id(), model.getSys_Class().getTable_id() };
		List<Sys_Room> list = this.getList(hql, object, 0, 0, "");
		if (null != list && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Sys_Room sr = list.get(0);
				sr.setState("0");
				this.updateT(sr);
			}
		}
		for (int i = 0; i < srlist.size(); i++) {
			Sys_Room_Position srp = srlist.get(i);
			srp.setSys_Room(model);
		}
		model.setListsrp(srlist);
		model.setStartClass(Common.getTime1());
		this.addT(model);

		return 1;
	}

	/**
	 * 查询当前学生的老师的教室
	 */
	@SuppressWarnings("all")
	@Override
	public Map getStudent_Teacher_Room(SysUser sysUser, SysUser teacher, String sys_class_table_id, String year) {
		// TODO Auto-generated method stub
		// 这里不需要查启用的主要原因，就是因为，老师可能给这个班画了几个教室了，这个学生上的是之前的老师，而不是当前的
		String hql = "select DISTINCT(t.table_id),t.x1,t.y1,t.state,max(t.startClass) from Sys_Room t left join t.sys_Class t1 left join t1.listsuc t2 where t.sysUser.table_id = ? and t1.table_id =? and t2.year = ? and t.state=1 group by t.table_id";
		Object[] obj = new Object[] { teacher.getTable_id(), sys_class_table_id, year };
		List<Object[]> srlist = this.getList(hql, obj, 0, 0, "");
		// 这上面是查询了这个学生和老师的在同一班的同一教师里，当然也在同一届里面的，，这个时间因为老师可能在教这个班的时候，会丛新
		// 画教室，而前面的教室会设为成状态为0,所以这后面的查询条件里面有一个有1
		// 得到这个教室，就可以将这个教室的位置发下去
		if (srlist == null || srlist.size() <= 0) {
			return null;
		}
		Object[] cbc = srlist.get(0);
		long ctime = Common.getTime1();
		// 表示系统中的下次开课时间太大了，目前时间还没有超过，没有可用的教室
		if (ctime < Long.parseLong(cbc[4].toString())) {
			return null;
		}
		// 拿到当前的教室
		long startClassTime = Long.parseLong(cbc[4].toString());
		Object[] objsrt = new Object[] { cbc[0], startClassTime };// 因为都课时的，哪边的课，只要对应这个课时，其实就可以知道这些位置信息了。
		// 这里将用户名称放在string1里面的
		String opt = "t.table_id, t.inTime, t.inTimeShow, t.state, t.startClass, t.startClassName, t.roomId, t.x1, t.y1,t.sysUser.userEngListName,t.sysUser.table_id,t.sysUser.userImage,t.sysUser.tell";
		String hql1 = "select new com.dream.model.Sys_Room_Position_User(" + opt + ") from Sys_Room_Position_User t where t.roomId = ? and t.startClass = ? ";
		List<Sys_Room_Position_User> sr = (List<Sys_Room_Position_User>) this.getList(hql1, objsrt, 0, 0, "");
		Map map = new HashMap();
		map.put("sys_Room", cbc);
		map.put("sys_Room_Position_User", sr);
		return map;
	}

	/**
	 * 学生自己选坐
	 */
	@Override
	public int addStudentRoomOption(Sys_Room model, SysUser su) {
		// TODO Auto-generated method stub
		String hql = "select count(*) from Sys_Room_Position_User t where  t.x1 = ? and t.y1 = ? and t.roomId = ? and t.startClass = ?";
		Object[] obj = new Object[] { model.getX1(), model.getY1(), model.getTable_id(), model.getStartClass() };
		int count = this.getListCount(hql, obj, "");
		if (count > 0) {
			return 2;
		}
		String dql = "delete from Sys_Room_Position_User t where t.sysUser.table_id = ? and t.roomId = ? and t.startClass = ? ";
		Object[] obj1 = new Object[] { su.getTable_id(), model.getTable_id(), model.getStartClass() };
		this.deleteT(dql, obj1);
		Sys_Room_Position_User srp = new Sys_Room_Position_User();
		srp.setX1(model.getX1());
		srp.setY1(model.getY1());
		srp.setStartClass(model.getStartClass());
		srp.setRoomId(model.getTable_id());
		srp.setSysUser(su);
		this.addT(srp);
		return 1;
	}

	/**
	 * 
	 * 查询相同的班级Code
	 */
	@Override
	public Sys_Class getSameClassCode(String cpassword) {
		// TODO Auto-generated method stub
		String hql = "from Sys_Class t where t.cpassword = ? ";
		Object[] obj = new Object[] { cpassword };
		Object tvtemp = (Object) this.getListOne(hql, obj, "");
		return (Sys_Class) tvtemp;
	}

	/**
	 * 
	 * 按注册码查找班级
	 * 
	 * 
	 */
	@Override
	public Sys_Class getzhucema(String mima) {
		// TODO Auto-generated method stub
		String hql = "from Sys_Class t where t.cpassword = ? ";
		Object[] obj = new Object[] { mima };
		Object tvtemp = (Object) this.getListOne(hql, obj, "");
		return (Sys_Class) tvtemp;
	}
	@Override
	public List<Sys_Class> getSysClassById(String classId) {
		// TODO Auto-generated method stub
		List<Sys_Class> list = new ArrayList<Sys_Class>();
		Sys_Class sc = (Sys_Class) this.getT(new Sys_Class(), classId);
		if (sc != null) {
			list.add(sc);
			selectParent(list, sc);
		}
		return list;
	}

	/**
	 * 查询自己所有的上级班级
	 * 
	 * @param list
	 * @param sc
	 */
	public void selectParent(List<Sys_Class> list, Sys_Class sc) {
		String cpid = sc.getCpid();
		if ("0".equals(cpid)) {

			return;
		} else {
			String hql = "from Sys_Class t where t.cid = ? ";
			Object[] obj = new Object[] { cpid };
			Sys_Class sc1 = (Sys_Class) this.getListOne(hql, obj, "");
			if (sc1 != null) {
				list.add(sc1);
				selectParent(list, sc1);
			}
		}
	};

}
